package edu.zut.cs.javaee.manager.controller;

import edu.zut.cs.javaee.manager.admin.AdminService;
import edu.zut.cs.javaee.manager.base.exception.GlobalException;
import edu.zut.cs.javaee.manager.student.StudentService;
import edu.zut.cs.javaee.manager.teacher.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
 * Log management
 * @author Is.f
 *
 */
@RestController
@RequestMapping("/")
public class LoginController {

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private AdminService adminService;

    @Autowired
    private ServletContext context;


    /**
     * 登录操作
     * @param userName 用户名
     * @param passWord 密码
     * @param role    角色 1管理员 2老师 3学生
     * @return
     */
    @PostMapping(value = "/doLogin")
    public ResponseEntity<Map<String,Object>> doLogin(String userName,String passWord,Integer role) throws Exception {
        List list = null;
        switch (role) {
            case 1: //管理员
                list = adminService.getUserInfo(userName,passWord);
                break;
            case 2://老师
                list = teacherService.getUserInfo(userName,passWord);
                break;
            case 3://学生
                list = studentService.getUserInfo(userName,passWord);
                break;
            default:
                throw new GlobalException("未知的角色");
        }
        if (ObjectUtils.isEmpty(list)) {
            throw new GlobalException("用户名或密码不正确");
        }
        Map<String,Object> map = new HashMap<String, Object>();
        String token = UUID.randomUUID().toString();
        map.put("token", token);
        map.put("user",list.get(0));
        context.setAttribute(token,list.get(0));
        return ResponseEntity.ok(map);

    }
}
